const { Service } = require("egg");
const qs = require("querystring");
class UserService extends Service {
  // 小程序微信登录
  async wxLogin(code) {
    const jscode2session = "https://api.weixin.qq.com/sns/jscode2session?";
    const { app, ctx } = this;
    const paramString = qs.stringify({
      appid: app.config.wx.appid,
      secret: app.config.wx.secret,
      js_code: code,
      grant_type: "authorization_code",
    });
    const res = await fetch(jscode2session + paramString);
    const data = await res.json();
    const userInfo = await ctx.model.Userinfo.findOne(
      { openid: data.openid },
    ).lean();
    if (userInfo) {
      //已登录
      const token = ctx.generateToken(userInfo._id);
      return { data: { ...userInfo, token }, msg: "成功" };
    } else {
      const newUserInfo = await ctx.model.Userinfo.create(
        { openid: data.openid }
      );
      const token = ctx.generateToken(newUserInfo._id);
      const {openid,...assets} = newUserInfo.toObject();
      return { msg: "成功", data: { ...assets, token } };
    }
  }
}
module.exports = UserService;
